<template>
  <el-dialog
  title="剧目详情"
  :visible.sync="showInfoVisible"
  :before-close="closedialog"
  @open="getdefault()"
  @close='clear()'
  :destroy-on-close="true"
  width="80%">
      <el-switch
      v-model="caneditshowinfo"
      active-color="#13ce66"
      inactive-color="#ff4949">
    </el-switch>
     <el-form :model="showinfo" ref="displayShowFormRef" :inline="true" :rules="displayRule">
       <el-divider>剧目基本信息</el-divider>
         <el-row ref="displayShowInfoDialogWidth">
           <el-col :span="10">
              <el-form-item prop="showName" label="剧目名称" >
                <el-input prefix-icon="el-icon-user-solid" v-model="showinfo.showName" :disabled="!caneditshowinfo"></el-input>
              </el-form-item>
           </el-col>
         </el-row>
         <el-row>
           <el-col :span="10">
              <el-form-item prop="theaterName" label="演出地点" >
                    <el-cascader
                      v-model="defaultlocations"
                      :options="locations"
                      :disabled="!caneditshowinfo"
                      @change="changedefaultlocations()"
                      >
                    </el-cascader>
                </el-form-item>
           </el-col>
           <el-col :span="10">
             <el-form-item prop="date" label="演出时间" >
                  <el-date-picker
                    type="dates"
                    v-model="showinfo.date"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                    :disabled="!caneditshowinfo"
                    :default-value='defaultTime'
                    @focus='getDefaultTime()'
                    >
                  </el-date-picker>
                </el-form-item>
           </el-col>
         </el-row>
         <el-row>
              <el-col :span="10">
                 <el-form-item prop="type" label="剧目类型" >
                   <el-input prefix-icon="el-icon-user-solid" v-model="showinfo.type" :disabled="!caneditshowinfo"></el-input>
                 </el-form-item>
              </el-col>
              <el-col :span="10">
                 <el-form-item prop="priceRange" label="价格分区" >
                   <el-input prefix-icon="el-icon-document"
                   v-model="showPrice"
                   :disabled="!caneditshowinfo"
                   @change="getpricearr()"
                   @focus="getoldpricearr()"
                   @input="replaceprice()"
                   ></el-input>
                 </el-form-item>
              </el-col>
          </el-row>
        <el-divider>座位图信息</el-divider>
        <!-- 座位图展示组件 -->
        <displayshowseatmap
        v-show="!caneditshowinfo"
        :showinfo="showinfo"
        :hallInfo="hallInfo"
        :seatSize="seatSize"
        :hall="defaultlocations"
        :price="showPrice"
        :caneditshowinfo="caneditshowinfo"></displayshowseatmap>
        <!-- 座位图编辑组件 -->
        <addshowseatmap
        v-show="caneditshowinfo"
        :hallInfo="hallInfo"
        :seatSize="seatSize"
        :price="showinfo.priceRange"
        :currentclass="currentclass"
        :showinfo="showinfo"
        :caneditshowinfo="caneditshowinfo"
        @changeshowinfo="changeshowinfo"></addshowseatmap>
       </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closedialog()">取 消</el-button>
        <el-button type="primary" @click="sendshowinfo()">确 定</el-button>
      </span>
</el-dialog>
</template>

<script>
// 导入子组件
import displayshowseatmap from './displayshowseatmap'
import addshowseatmap from './addshowseatmap'
// 导入网络请求
import { getLocations, postshowseatmap, postshowinfo } from '../../../network/showManage'
export default {
  name: 'displayshowinfo',
  components: { displayshowseatmap, addshowseatmap },
  props: {
    showInfoVisible: {
      type: Boolean,
      default: false
    },
    currentshowinfo: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  watch: {
    currentshowinfo () {
      console.log('get showinfo')
      this.showinfo = this.currentshowinfo
    }
  },
  data () {
    return {
      defaultTime: '',
      // 当前演出的信息
      showinfo: {},
      // 级联选择器数组
      locations: [],
      // 级联选择器默认数据
      defaultlocations: [],
      // 价格区间字符串
      showPrice: '',
      // 原价格区间
      oldShowPrice: '',
      // 当前剧目的价格图
      pricemap: [],
      // 当前对话框的宽度
      seatMapSize: 0,
      seatSize: '',
      hallInfo: {},
      // 这个展示页面是否可编辑
      caneditshowinfo: false,
      // 可编辑状态，几个输入框要能输入，并且下面的seatmap要换成addshowseatmap的组件
      // 当前选中的座位等级
      currentclass: -1,
      // 剧目信息表单验证规则
      displayRule: {
        // 剧目名称
        showName: [
          // 必须要输入
          { required: true, message: '请输入剧目名称', trigger: 'blur' },
          // 输入长度在2~60之间
          { min: 2, max: 60, message: '长度必须大于2', trigger: 'blur' }
        ],
        // 演出地址，这里我们级联选择器必须选择，所以可以不需要验证
        theaterName: [
          { required: true }
        ],
        // 演出日期
        date: [
          { required: true, message: '请选择日期', trigger: 'blur' }
        ],
        // 演出类型
        type: [
          { required: true, message: '请输入剧目类型', trigger: 'blur' }
        ],
        // 价格区间 通过validator来验证更多细节
        priceRange: [
          { required: true, message: '请输入价格区间', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 关闭对话框
    closedialog () {
      this.$emit('closeShowInfoDialog')
      this.$nextTick(() => {
        this.caneditshowinfo = false
      })
    },
    // 获取级联选择器数据
    getlocation () {
      // this.$axios.get('http://localhost:3033/getlocation')
      getLocations().then(res => {
        this.locations = res.data.location
      })
    },
    // 这个函数在对话框打开的时候才会获取
    getdefault () {
      // console.log(this.seatMapSize)
      // 获取当前剧目的演出场所来设置级联选择器的默认值
      this.getlocation()
      this.showinfo = this.currentshowinfo
      // 获取当前价格图数据
      this.pricemap = this.showinfo.pricemap
      this.defaultlocations = []
      let theaterindex = this.locations.findIndex(item => {
        return item.label === this.showinfo.theaterName
      })
      let hallindex = this.locations[theaterindex].children.findIndex(item => {
        return item.label === this.showinfo.hall
      })
      this.defaultlocations.push(this.locations[theaterindex]['value'], this.locations[theaterindex].children[hallindex]['value'])
      // console.log(theaterindex, hallindex, this.defaultlocations)
      // 将showinfo内的价格数组处理成字符串
      let arr = []
      for (let i = 0; i < this.showinfo.priceRange.length; i++) {
        arr.push(this.showinfo.priceRange[i].price)
      }
      // console.log(arr)
      this.showPrice = arr.join(',')
      // this.$axios.post('http://localhost:3033/addshowseatmap', {
      //   'path': this.defaultlocations[0],
      //   'id': this.defaultlocations[1]
      // })
      postshowseatmap(this.defaultlocations[0], this.defaultlocations[1]).then(res => {
        // console.log(res)
        this.hallInfo = res.data.hallData
        // this.seatMapSize = Math.floor(document.body.offsetWidth * 0.8 - 40)
        this.seatMapSize = this.$refs.displayShowFormRef.$el.offsetWidth - 18
        this.seatSize = this.seatMapSize / this.hallInfo.hallWidth + 'px'
        // console.log(this.seatMapSize, this.seatSize)
      })
    },
    // 当剧目价格input修改的时候，这个字符串要重新处理成数组形式并且给到showinfo
    // 同时还要根据这个input的值修改showinfo中的pricemap数据，删除对应的数据
    getpricearr () {
      if (this.showPrice !== '') {
        // 旧的input价格数组转换成数字数组并且排序
        let oldarr = this.oldShowPrice.split(',')
        for (let i = 0; i < oldarr.length; i++) {
          oldarr[i] = oldarr[i] * 1
        }
        oldarr.sort((a, b) => { return a - b })
        // 新的input数据转换成数组
        let arr = this.showPrice.split(',')
        // 转换成数字数组
        for (let i = 0; i < arr.length; i++) {
          arr[i] = arr[i] * 1
        }
        // 因为进行了更改，所以会对arr进行重新排序，使用sort()
        arr.sort((a, b) => { return a - b })
        // 重新传给输入框
        this.showPrice = arr.join(',')
        // 重新造一个数组对象赋值给priceRange
        let newarr = []
        // 分为3种情况
        if (oldarr.length > arr.length) {
        // 情况1 oldShowPrice > showPrice 代表是删除了数据
          console.log('删除了价格等级')
          // 创建新的price
          for (let i = 0; i < arr.length; i++) {
            let newprice = {}
            newprice.class = i
            newprice.price = arr[i]
            newarr.push(newprice)
          }
          // 把生成的新数组放入priceRange
          this.showinfo.priceRange = newarr
          // 根据这个newarr来生成新的pricemap
          // 要区这个数据是添加了数据还是删除了数据
          let newpricemap = []
          for (let j = 0; j < newarr.length; j++) {
            let index = this.showinfo.pricemap.findIndex(item => {
              return item.price === newarr[j].price
            })
            this.showinfo.pricemap[index].class = j
            newpricemap.push(this.showinfo.pricemap[index])
          }
          this.showinfo.pricemap = newpricemap
        } else if (oldarr.length < arr.length) {
        // 情况2如果新输入的值比之前存入的值要长，那么我们是输入了一个新的价格
          console.log('添加了新的价格等级')
          // 创建新的price，并且传递给showinfo
          for (let i = 0; i < arr.length; i++) {
            let newprice = {}
            newprice.class = i
            newprice.price = arr[i]
            newarr.push(newprice)
          }
          this.showinfo.priceRange = newarr
          // console.log(newarr)
          // 根据这个newarr来生成新的pricemap
          let newpricemap = []
          // 先把价格相同的数据拿出来重新设定等级
          for (let j = 0; j < newarr.length; j++) {
            let index = this.showinfo.pricemap.findIndex(item => {
              return item.price === newarr[j].price
            })
            let newmap = {}
            newmap.class = j
            // console.log(index)
            if (index !== -1) {
            // 当前价位是存在于之前的价格数据中的，那就要修改之前pricemap的class等级数据
              newmap.price = this.showinfo.pricemap[index].price
              newmap.id = this.showinfo.pricemap[index].id
              newpricemap.push(newmap)
            } else {
            // 如果这个数据不存在于之前的pricemap中，就要新建一个等级数据
              newmap.price = newarr[j].price
              newmap.id = []
              newpricemap.push(newmap)
            }
          }
          this.showinfo.pricemap = newpricemap
        } else {
        // 这里是第3种情况，前后两次数组的长度不变，但是内容改变了
        // console.log(arr, oldarr)
        // 此时2个数组的长度都没有变化，只需要判断同位置的价格是否相等然后处理即可
          for (let i = 0; i < arr.length; i++) {
            if (arr[i] !== oldarr[i]) {
              this.showinfo.pricemap[i].price = arr[i]
            }
          }
        }
      } else {
        console.log('pricerange为空')
        this.showinfo.priceRange = []
        this.showinfo.pricemap = []
      }
    },
    // 在input有的时候就要，保存之前的价格数据
    getoldpricearr () {
      console.log('保存老数据')
      this.oldShowPrice = this.showPrice
    },
    // 获取日期选择器中的默认日期数据
    getDefaultTime () {
      let datearr = []
      let day = new Date()
      // console.log(this.showinfo.date)
      datearr = this.showinfo.date.split('-')
      day.setFullYear(datearr[0])
      day.setMonth(datearr[1] - 1)
      day.setDate(datearr[2])
      this.defaultTime = day
    },
    // 清除数据
    clear () {
      this.showinfo = {}
    },
    // 用于接收addshowseatmap传递过来的数据
    changeshowinfo (ccshowinfo) {
      console.log('changeshowinfo')
      this.showinfo = ccshowinfo
    },
    // 将传入的字符串里的中文逗号转换成英文逗号
    replaceprice () {
      this.showPrice = this.showPrice.replace(/，/ig, ',')
    },
    // 点击确定之后需要发送数据给后台
    sendshowinfo () {
      let len = this.showinfo.priceRange.length - 1
      this.showinfo.price = `${this.showinfo.priceRange[0].price}-${this.showinfo.priceRange[len].price}`
      // this.$axios.post('http://localhost:3033/changeshow', this.showinfo)
      postshowinfo(this.showinfo).then(res => {
        // 向父组件发送事件，提醒重新获取数据
        this.$emit('showchanged')
        // 关闭对话框
        this.closedialog()
      })
    },
    // 根据级联选择器来重新设置seatmap
    changedefaultlocations () {
      // 更具当前级联选择器的值来获取seatmap
      console.log(this.defaultlocations)
      // this.$axios.post('http://localhost:3033/addshowseatmap', {
      //   'path': this.defaultlocations[0],
      //   'id': this.defaultlocations[1]
      // })
      postshowseatmap(this.defaultlocations[0], this.defaultlocations[1]).then(res => {
        // 先清空当前剧目的seatmap
        this.seatMapSize = 0
        this.seatSize = 0
        this.showinfo.pricemap = []
        this.showinfo.priceRange = []
        this.showPrice = ''
        // 然后我们需要获取到新的seatmap
        this.hallInfo = res.data.hallData
        this.$nextTick(() => {
          this.seatMapSize = Math.floor(document.body.offsetWidth * 0.8 - 58)
          this.seatSize = this.seatMapSize / this.hallInfo.hallWidth + 'px'
          console.log(this.seatMapSize, this.seatSize)
          let theaterindex = this.locations.findIndex(item => {
            return item.value === this.defaultlocations[0]
          })
          // 我们这里需要更改showinfo内的hall/theater/theaterName
          this.showinfo.hall = res.data.currentdata.hallName
          this.showinfo.theater = this.defaultlocations[0]
          this.showinfo.theaterName = this.locations[theaterindex]['label']
        })
      })
    }
  },
  mounted () {
    this.getlocation()
    this.showinfo = this.currentshowinfo
    // 获取当前价格图数据
    this.pricemap = this.showinfo.pricemap
    this.oldShowPrice = this.showPrice
  }
}
</script>

<style lang="stylus" scoped>

</style>
